import React, { useState } from 'react';
import axios from 'axios';

const Login = ({ setToken }) => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.post('/api/auth/login', { username, password });
            setToken(response.data.token);
            localStorage.setItem('token', response.data.token);
            alert('登录成功！');
        } catch (error) {
            console.error('登录失败:', error);
            alert('登录失败，请检查用户名和密码。');
        }
    };

    return (
        <div className="login-container">
            <h2>登录</h2>
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label>用户名:</label>
                    <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label>密码:</label>
                    <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
                </div>
                <button type="submit">登录</button>
            </form>
        </div>
    );
};

export default Login;

